package com.bw.user.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.user.domain.User;
import com.bw.user.service.UserService;
import com.bw.user.units.Result;
import com.macro.cloud.gitee.domain.GiteeClientUserDto;
import com.macro.cloud.gitee.service.Oauth2ClientService;

import com.ruoyi.common.core.utils.JwtUtils;
import com.sun.deploy.security.BlockedException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.Session;
import javax.mail.Store;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Oauth2ClientService oauth2ClientService;
//    @GlobalTransactional
    @RequestMapping("/list")
    public Result list(){
        List<User> list = userService.list();
        return Result.success(list);
    }
    @RequestMapping("/login")
    public Result login(@RequestBody User user){
        String code = (String) redisTemplate.opsForValue().get(user.getUid());
        if(!code.equals(user.getCodepwd())){
            return Result.fail("验证码不存在");
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUname,user.getUname());
        User one = userService.getOne(userLambdaQueryWrapper);
        if(one==null){
            return Result.fail("用户名不存在");
        }
        if(!one.getPwd().equals(user.getPwd())){
            return Result.fail("密码不存在");
        }

        return Result.success("好凶啊");
    }
    @RequestMapping("/checkcode")
    public Result checkcode(String uid){
        Long increment = redisTemplate.opsForValue().increment(uid+"click", 1);
        if(increment>3){
            return Result.fail("操作频繁");
        }else{
            return Result.success();
        }
    }
    @RequestMapping("/getcode")
    public void getcode(String uid,HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid,captcha.getCode(),1, TimeUnit.MINUTES);
    }
    @Autowired
    private HttpServletRequest request;
    @RequestMapping("/callbackCode")
    public Result callbackCode(String code,HttpServletResponse response) throws IOException {
        System.out.println("接收到的临时授权码 " + code);
        String accessToken1 = oauth2ClientService.getAccessToken(code);
        System.out.println("根据临时授权码获取到的token " + accessToken1);
        GiteeClientUserDto currentUser = oauth2ClientService.getCurrentUser(accessToken1);


        Integer giteeId = currentUser.getId();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getGiteeId,giteeId);
        User userDB = userService.getOne(userLambdaQueryWrapper);
        if(userDB==null){
            return Result.fail("用户不存在");
        }else{
            userDB.setNickName(currentUser.getName());
            userDB.setAvatarUrl(currentUser.getAvatar_url());
            userService.updateById(userDB);
        }
        // 加密用户信息 得到token,设置30分钟有效期  把token放入cookie  cookie过期时间也是30a分钟 把cookie返回给浏览器
        String token = JwtUtils.createToken(BeanUtil.beanToMap(userDB));
        Cookie token1 = new Cookie("token", token);
        token1.setMaxAge(1000*60*30);
        response.addCookie(token1);
        String loginIp = request.getRemoteAddr();

//        // 判断之前是否已经注册过用户
//        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        userLambdaQueryWrapper.eq(User::getGiteeId,giteeId);
//        User userDB = userService.getOne(userLambdaQueryWrapper);
//        if (userDB == null){
//            userDB = new User();
//            userDB.setUname(name);
//            userDB.setGiteeId(giteeId);
//            userDB.setAvatarUrl(avatarUrl);
//            userDB.setNickName(nickName);
//            userService.save(userDB);
//        }else {  //如果之前已经注册过， 更新一下用户的昵称和头像
//            userDB.setNickName(nickName);
//            userDB.setAvatarUrl(avatarUrl);
//            userService.updateById(userDB);
//        }

        userDB.setToken(token);

        //防止异地登录
        String lastIp = (String) redisTemplate.opsForValue().get("login:" + userDB.getId() + ":ip");
        //是否重复登录
        if(redisTemplate.hasKey("login:"+userDB.getId())){
            if(!loginIp.equals(lastIp) && loginIp!=null){
                return Result.fail("请勿异地登录");
            }
            String lasttoken = (String) redisTemplate.opsForValue().get("login:" + userDB.getId());
            redisTemplate.delete("login:" + userDB.getId());
            redisTemplate.delete("login:" +lasttoken);
            return Result.fail("请勿重复登录");
        }

        //  登录成功去列表页  在列表页展示昵称和头像
        redisTemplate.opsForValue().set("login:"+token,userDB);
        redisTemplate.opsForValue().set("login:"+userDB.getId(),token);
        redisTemplate.opsForValue().set("login:"+userDB.getId()+":ip",loginIp);
        return Result.success(userDB);

    }



    @RequestMapping("/OauthUrl")
    public Result OauthUrl(){
        String oauth2CodeUrl = oauth2ClientService.getOauth2CodeUrl();
        return Result.success(oauth2CodeUrl);
    }

//    @SentinelResource(value = "nihao",blockHandler = "nihaoya")
//    @RequestMapping("/test")
//    public String tsest() throws InterruptedException {
//        Thread.sleep(1000);
//        return "ckdvn";
//    }
//    public String nihaoya(BlockedException e) throws InterruptedException {
//        return "降级";
//    }
    @RequestMapping("/logina")
    public Result logina(@RequestBody User user){
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUname,user.getUname());
        User one = userService.getOne(userLambdaQueryWrapper);
        if(one==null){
            return Result.fail("用户名不存在");
        }
        if(!one.getPwd().equals(user.getPwd())){
            return Result.fail("密码不存在");
        }

        String token = JwtUtils.createToken(BeanUtil.beanToMap(one));
        return Result.success(token);
    }

}
